package com.zou.application.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;


@Configuration
@EnableMongoRepositories
// 读取配置文件的，通过Environment读取
@PropertySource("classpath:application.yml")
public class MongonTemplateConfig extends AbstractMongoConfiguration{
	
	@Autowired
	private Environment env;
	
	@Override
	public MongoClient mongoClient() {
		return new MongoClient(env.getProperty("host"));
	}

	@Override
	protected String getDatabaseName() {
		return env.getProperty("database");
	}
	
	@Bean
	public MongoTemplate getMongoTemplate(){
		return new MongoTemplate(mongoDbFactory());
	}
	
	@Bean
    public MongoDbFactory mongoDbFactory() {
		MongoDbFactory mongoDbFactory =  new SimpleMongoDbFactory(new MongoClient(env.getProperty("host"), env.getProperty("port", Integer.class)), getDatabaseName());
        return mongoDbFactory;
    }
}
